package com.silknet.general;

import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.silknet.db.DBConnection;
import com.silknet.db.DBOperations;
import com.silknet.images.ImageStore;
import com.silknet.images.Object_type;

public class HtmlProcessor {

	private static AtomicBoolean initialised = new AtomicBoolean(false);
	private static TreeMap<Integer, Object_type> objectTypesFull;
	private static TreeMap<Integer, Object_type> objectTypesStructured;
	private static String menu;
	private static String comboMenu;
	private static TransformerFactory tf = TransformerFactory.newInstance();

	private static void init(HttpServletRequest request, ServletContext context)
			throws Exception {
		if (!initialised.get()) {
			Connection con = null;
			try {
				con = DBConnection.getConnection("FlyComp");
				objectTypesFull = DBOperations.getObjectTypes(con, request,
						context);
				TreeMap<Integer, Object_type> result = new TreeMap<Integer, Object_type>();

				Collection<Object_type> values = objectTypesFull.values();
				for (Object_type value : values) {
					value.setParentAndChilds(objectTypesFull);
					if (value.getParent_id() == 0)
						result.put(value.getObjt_id(), value);
				}
				// TreeMap<Integer, ArrayList<Object[]>> objectNames =
				// getObjectNames(con);
				StringBuffer sb = new StringBuffer(
						"<ul class=\"tree\" style=\"margin-left: 15px;\">");
				Collection<Object_type> resultValues = result.values();
				List<Object_type> list = new ArrayList<Object_type>(
						resultValues);
				Collections.sort(list, new Comparator<Object_type>() {
					public int compare(Object_type o1, Object_type o2) {
						return o1.getType_name().compareTo(o2.getType_name());
					}
				});
				JSONArray jsn = new JSONArray();
				JSONObject jsnO = new JSONObject();
				jsnO.put("id", -1);
				jsnO.put("text", "All");
				jsn.add(jsnO);
				for (Object_type value : list) {
					jsn.add(value.generateComboMenu());
					value.generateMenu(sb, "\t");
				}
				sb.append("</ul>");
				menu = sb.toString();
				comboMenu = jsn.toString();
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception(e.getMessage());

			} finally {

				try {
					con.close();
				} catch (Exception e2) {
				}
			}
			initialised.set(true);
		}
	}

	public static String getPointNames(HttpServletRequest request,
			ServletContext context) {
		try {
			init(request, context);
			String query = request.getParameter("query");
			String objecttype = request.getParameter("object_type");
			int object_type = -1;
			try {
				object_type = Integer.parseInt(objecttype);
			} catch (Exception e) {
				// TODO: handle exception
			}
			query = query.trim();
			JSONObject jo = new JSONObject();
			jo.put("query", query);

			// StringBuffer sb = new StringBuffer("{\n\tquery:'" + query +
			// "',");
			ArrayList<String> result = DBOperations.getSpacialMapPointNames(
					query, object_type);
			// sb.append("\n\tsuggestions:[");
			JSONArray jsaValues = new JSONArray();
			boolean once = false;
			for (String data : result) {
				String s = data.trim();
				jsaValues.add(s);
			}
			jo.put("suggestions", jsaValues);
			// jsaValues = new JSONArray();
			// jsaValues.add(query);
			// jsaValues.add(query.toLowerCase());
			// jsaValues.add(query.toUpperCase());
			jo.put("data", jsaValues);
			// sb.append("],\n\tdata:['" + query + "','" + query.toLowerCase() +
			// "','"
			// + query.toUpperCase() + "']\n}");
			String s = jo.toString();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}

	public static String getStreetNames(HttpServletRequest request,
			ServletContext context) {
		try {
			init(request, context);
			String query = request.getParameter("query");
			
			
			query = query.trim();
			JSONObject jo = new JSONObject();
			jo.put("query", query);

			// StringBuffer sb = new StringBuffer("{\n\tquery:'" + query +
			// "',");
			ArrayList<String> result = DBOperations.getStreetNames(
					query);
			// sb.append("\n\tsuggestions:[");
			JSONArray jsaValues = new JSONArray();
			boolean once = false;
			for (String data : result) {
				String s = data.trim();
				jsaValues.add(s);
			}
			jo.put("suggestions", jsaValues);
			// jsaValues = new JSONArray();
			// jsaValues.add(query);
			// jsaValues.add(query.toLowerCase());
			// jsaValues.add(query.toUpperCase());
			jo.put("data", jsaValues);
			// sb.append("],\n\tdata:['" + query + "','" + query.toLowerCase() +
			// "','"
			// + query.toUpperCase() + "']\n}");
			String s = jo.toString();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}

	public static String getMenu(HttpServletRequest request,
			ServletContext context) throws Exception {
		init(request, context);
		return menu;
	}

	public static String getSearchObjectTypes(HttpServletRequest request,
			ServletContext context) throws Exception {
		init(request, context);

		return comboMenu;
	}

	public static String getObjectInfo(HttpServletRequest request,
			ServletContext context) throws Exception {
		init(request, context);
		Connection con = null;
		try {
			con = DBConnection.getConnection("FlyComp");
			int id = Integer.parseInt(request.getParameter("id"));
			int type_id = Integer.parseInt(request.getParameter("type_id"));
			String[] templates = DBOperations.getTemplateObjectTypeID(type_id,
					con);
			String object_XML = DBOperations.getObjectByTemplate(id,
					templates[0], con);
			object_XML = "<?xml version=\"1.0\"?><ROW>" + object_XML + "</ROW>";
			SAXSource ss = new SAXSource(new InputSource(new StringReader(
					templates[1])));
			Transformer t = tf.newTransformer(ss);
			StringWriter sw = new StringWriter();
			t.setParameter("img_url", ImageStore.ICONS_DIR + "/");
			ss = new SAXSource(new InputSource(new StringReader(object_XML)));
			t.transform(ss, new StreamResult(sw));
			String result = sw.getBuffer().toString();
			sw.close();
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				con.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

	}
}
